﻿using System;
using System.Windows.Input;

namespace BattleFury.Server.Wpf.Core.Commands
{
	public class DelegateCommand
		: ICommand
	{
		private readonly object _forcedParameter;
		private readonly Predicate<object> _canExecute;
		private readonly Action<object> _execute;

		public event EventHandler CanExecuteChanged;


		public DelegateCommand(Action<object> execute)
			: this(execute, null)
		{
		}

		public DelegateCommand(Action<object> execute, object forcedParameter)
			: this(execute, null)
		{
			_forcedParameter = forcedParameter;
		}

		public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
		{
			_execute = execute;
			_canExecute = canExecute;
		}

		public bool CanExecute(object parameter)
		{
			return _canExecute == null || _canExecute(parameter);
		}

		public void Execute(object parameter)
		{
			if (_forcedParameter != null && parameter == null)
				parameter = _forcedParameter;
			_execute(parameter);
		}

		public void RaiseCanExecuteChanged()
		{
			if (CanExecuteChanged != null)
			{
				CanExecuteChanged(this, EventArgs.Empty);
			}
		}
	}
}